<?php
/*********************************************
  CPG Dragonfly™ CMS
  ********************************************
  Copyright © 2004 - 2005 by CPG-Nuke Dev Team
  http://www.dragonflycms.com

  Dragonfly is released under the terms and conditions
  of the GNU GPL version 2 or any later version
**********************************************/
if (!defined('ADMIN_PAGES')) { exit; }
require_once('includes/nbbcode.php');
require_once('modules/News/admin/functions.inc');

Dragonfly_Page::setTitle('. '._BC_DELIM.' '._ARTICLEADMIN);

Dragonfly_Output_Js::add('includes/poodle/javascript/bbcode.js');
Dragonfly_Output_Css::add('bbcode');

if (isset($_POST['mode']))
{
	$story = array(
		'catid'      => intval($_POST['catid']),
		'title'      => $_POST['subject'],
		'hometext'   => $_POST['hometext'],
		'bodytext'   => $_POST['bodytext'],
		'topic'      => intval($_POST['topic']),
		'notes'      => empty($_POST['notes']) ? '' : $_POST['notes'],
		'ihome'      => !empty($_POST['ihome']),
		'alanguage'  => $_POST['alanguage'],
		'acomm'      => !empty($_POST['acomm']),
		'associated' => empty($_POST['assotop']) ? '' : implode(',', $_POST['assotop']),
		'ptime'      => empty($_POST['publish_time']) ? time() : strtotime($_POST['publish_time']),
	);

	if ('save' == $_POST['mode'])
	{
		if (isset($_GET['edit']))
		{
			$story['display_order'] = intval($_POST['display_order']);
			$db->TBL->stories->update($story, 'sid='.intval($_GET['edit']));
			$db->TBL->poll_desc->update(array('poll_ptime' => $story['ptime']), 'artid='.intval($_GET['edit']));
		}
		else
		{
			$story['aid']       = is_admin();
			$story['informant'] = ($userinfo['user_id']>1) ? $userinfo['username'] : $story['aid'];
			$story['poll_id']   = 0;

			$option_text = !empty($_POST['option_text']) ? $_POST['option_text'] : '';
			if (!empty($_POST['poll_title']) && !empty($option_text[0]) && !empty($option_text[1])) {
				$story['poll_id'] = $db->TBL->poll_desc->insert(array(
					'poll_title' => $_POST['poll_title'],
					'poll_ptime' => $story['ptime'],
					'time_stamp' => time(),
					'voters'     => 0,
					'planguage'  => $story['alanguage'],
					'artid'      => 0,
					'comments'   => $story['acomm']
				),'poll_id');
				for ($i = 0; $i < count($option_text); ++$i)
				{
					$db->TBL->poll_data->insert(array(
						'poll_id'      => $story['poll_id'],
						'option_text'  => $option_text[$i],
						'option_count' => 0,
						'vote_id'      => $i
					));
				}
			}

			$story['comments'] = $story['counter'] = $story['score'] = $story['ratings'] = 0;
			$story['display_order'] = intval($_POST['display_order']);

			$artid = $db->TBL->stories->insert($story, 'sid');
			if ($story['poll_id']) {
				$db->exec("UPDATE {$db->TBL->poll_desc} SET artid={$artid} WHERE poll_id={$story['poll_id']}");
			}

			$db->exec("UPDATE {$db->TBL->admins} SET counter=counter+1 WHERE aid='{$story['aid']}'");
		}
		URL::redirect(URL::admin('News'));
	}

	else if ($_POST['mode'] == 'preview')
	{
		Dragonfly_Page::setTitle('. '._BC_DELIM.' '._PREVIEWSTORY);

		$story['associated'] = explode(',',$story['associated']);
		list($story['topicimage']) = $db->uFetchRow("SELECT topicimage FROM {$db->TBL->topics} WHERE topicid={$story['topic']}");

		if (Dragonfly_Modules::isActive('Surveys'))
		{
			$story['poll'] = array(
				'title'   => $_POST['poll_title'],
				'options' => $_POST['option_text'],
			);
		}

		$TPL = Dragonfly::getKernel()->OUT;
		$TPL->story      = $story;
		$TPL->view_story = true;
		$TPL->topics     = $db->query("SELECT topicid id, topictext label FROM {$db->TBL->topics} ORDER BY topictext");
		$TPL->categories = $db->query("SELECT catid id, title label FROM {$db->TBL->stories_cat} ORDER BY title");
		$TPL->display('News/admin/edit');
	}
}

else if (isset($_GET['edit']))
{
	Dragonfly_Page::setTitle('. '._BC_DELIM.' '._EDITARTICLE);

	$story = $db->uFetchAssoc("SELECT
		sid, catid, title, hometext, bodytext, topic, notes, ihome, alanguage, acomm, topicimage, associated, display_order
	FROM {$db->TBL->stories}
	LEFT JOIN {$db->TBL->topics} ON (topicid=topic)
	WHERE sid=".intval($_GET['edit']));
	$story['associated'] = explode(',',$story['associated']);

	$TPL = Dragonfly::getKernel()->OUT;
	$TPL->story      = $story;
	$TPL->view_story = true;
	$TPL->topics     = $db->query("SELECT topicid id, topictext label FROM {$db->TBL->topics} ORDER BY topictext");
	$TPL->categories = $db->query("SELECT catid id, title label FROM {$db->TBL->stories_cat} ORDER BY title");
	$TPL->display('News/admin/edit');
}

else if (isset($_GET['del']))
{
	$sid = intval($_GET['del']);
	if (isset($_POST['cancel'])) { URL::redirect(URL::admin()); }
	if (isset($_POST['confirm'])) {
		if ($CPG_SESS['admin']['page'] != 'News') { cpg_error(_ERROR_BAD_LINK, _SEC_ERROR); }
		$db->exec("DELETE FROM {$db->TBL->stories} WHERE sid={$sid}");
		$db->exec("DELETE FROM {$db->TBL->comments} WHERE sid={$sid}");
		//$db->exec("UPDATE {$db->TBL->poll_desc} SET artid=0 WHERE artid={$sid}");
		list($poll_id) = $db->uFetchRow("SELECT poll_id FROM {$db->TBL->poll_desc} WHERE artid={$sid}");
		if ($poll_id) {
			$db->exec("DELETE FROM {$db->TBL->poll_desc} WHERE poll_id={$poll_id}");
			$db->exec("DELETE FROM {$db->TBL->poll_data} WHERE poll_id={$poll_id}");
		}
		URL::redirect(URL::admin());
	}
	cpg_delete_msg(URL::admin('&amp;del='.$sid), sprintf(_ERROR_DELETE_CONF, 'this story'));
}

else if (isset($_GET['mode']))
{
	if (substr($_GET['mode'],0,3) == 'cat')
	{
		require_once('modules/News/admin/categories.inc');
	}
	else
	{
		$TPL = Dragonfly::getKernel()->OUT;
		if ($_GET['mode'] == 'add')
		{
			$story = array(
				'catid'    => 0,
				'topic'    => 0,
				'ihome'    => 1,
				'acomm'    => $MAIN_CFG->global->articlecomm,
				'ptime'    => null,
				'subject'  => '',
				'hometext' => '',
				'bodytext' => '',
				'alanguage' => '',
				'associated' => array(),
				'display_order' => 0,
			);
			if (Dragonfly_Modules::isActive('Surveys'))
			{
				$story['poll'] = array(
					'title'=>true,
					'options'=>array('','','','','','','','','','','',''),
				);
			}
			$TPL->story      = $story;
			$TPL->topics     = $db->query("SELECT topicid id, topictext label FROM {$db->TBL->topics} ORDER BY topictext");
			$TPL->categories = $db->query("SELECT catid id, title label FROM {$db->TBL->stories_cat} ORDER BY title");
			$TPL->display('News/admin/edit');
		}
	}
}

else if (isset($_GET['disporder']))
{
	$db->exec("UPDATE {$db->TBL->stories} SET display_order=".intval($_GET['disporder'])." WHERE sid=".intval($_GET['sidrep']));
	$db->exec("UPDATE {$db->TBL->stories} SET display_order=".intval($_GET['disporderrep'])." WHERE sid=".intval($_GET['sidori']));
	URL::redirect(URL::admin('News'));
}

else if (isset($_GET['unstick']))
{
	$db->exec("UPDATE {$db->TBL->stories} SET display_order=0 WHERE sid=".intval($_GET['unstick']));
	URL::redirect(URL::admin('News'));
}

else if (isset($_GET['stick']))
{
	list($sticky) = $db->uFetchRow("SELECT MAX(display_order) AS maxnumber FROM {$db->TBL->stories}");
	++$sticky;
	$db->exec("UPDATE {$db->TBL->stories} SET display_order={$sticky} WHERE sid=".intval($_GET['stick']));
	URL::redirect(URL::admin('News'));
}

else
{
	show_head();

	echo '<span><strong>'._AUTOMATEDARTICLES.'</strong></span><br /><br />';
	$result = $db->query("SELECT sid, aid, title, ptime, alanguage FROM {$db->TBL->stories} WHERE ptime>".time()." ORDER BY ptime ASC");
	if ($result->num_rows) {
		echo '<table>';
		while (list($sid, $said, $title, $ptime, $alanguage) = $result->fetch_row())
		{
			if ($alanguage == '') { $alanguage = _ALL; }
			$ptime = Dragonfly::getKernel()->L10N->date('DATE_F', $ptime);
			echo "<tr>
				<td width=\"100%\">$title</td>
				<td>$alanguage</td>
				<td nowrap=\"nowrap\">$ptime</td>";
			if (can_admin('news')) {
				echo '<td nowrap="nowrap">(<a href="'.URL::admin("News&amp;edit=$sid").'">'._EDIT.'</a>-<a href="'.URL::admin("News&amp;del=$sid").'">'._DELETE."</a>)</td>";
			}
			echo "</tr>";
		}
		echo '</table>';
	} else {
		echo sprintf(_ERROR_NONE_TO_DISPLAY,strtolower(_AUTOMATEDARTICLES));
	}

	echo '<br /><br /><span><strong>'._STICKY.'</strong></span><br /><br />';
	$result = $db->query("SELECT sid, aid, title, alanguage, display_order FROM {$db->TBL->stories}
		LEFT JOIN {$db->TBL->topics} AS t ON (topicid=topic)
		WHERE display_order <> '0'
		  AND ptime<=".time()."
		ORDER BY display_order DESC");
	if ($result->num_rows) {
		echo '<table>';
		while (list($sid, $said, $title, $alanguage, $display_order) = $result->fetch_row()) {
			$disporder = is_null($display_order) ? '&nbsp;' : $display_order;
			$disporder3 = $disporder - 1;
			$disporder1 = $disporder + 1;
			list($sid1) = $db->uFetchRow("SELECT sid FROM {$db->TBL->stories} WHERE display_order='{$disporder1}'");
			list($sid2) = $db->uFetchRow("SELECT sid FROM {$db->TBL->stories} WHERE display_order='{$disporder3}'");
			if ($alanguage == '') { $alanguage = _ALL; }
			echo "<tr><td><strong>$sid</strong>"
				."</td><td width=\"100%\"><a href=\"".URL::index("News&amp;file=article&amp;sid=$sid")."\">$title</a>"
				."</td><td>$alanguage"
				."<td>";
			if ($sid1) {
				echo '<a href="'.URL::admin("News&amp;disporder=$disporder&amp;sidori=$sid&amp;disporderrep=$disporder1&amp;sidrep=$sid1")."\"><img src=\"images/up.gif\" alt=\""._ARTICLEUP."\" title=\""._ARTICLEUP."\" border=\"0\" hspace=\"3\" /></a>";
			}
			if ($sid2 && $disporder3 <> '0') {
				echo '<a href="'.URL::admin("News&amp;disporder=$disporder&amp;sidori=$sid&amp;disporderrep=$disporder3&amp;sidrep=$sid2")."\"><img src=\"images/down.gif\" alt=\""._ARTICLEDOWN."\" title=\""._ARTICLEDOWN."\" border=\"0\" hspace=\"3\" /></a>";
			}
			echo '</td><td>'.$disporder.'</td>';
			if (can_admin('news')) {
				echo "<td nowrap=\"nowrap\">(<a href=\"".URL::admin("News&amp;edit=$sid").'">'._EDIT."</a>-<a href=\"".URL::admin("News&amp;del=$sid").'">'._DELETE."</a>-<a href=\"".URL::admin("News&amp;unstick=$sid").'">'._UNSTICK.'</a>)</td>';
			}
			echo '</tr>';
		}
		echo '</table>';
	} else {
		echo sprintf(_ERROR_NONE_TO_DISPLAY,strtolower(_STICKY));
	}

	echo '<br /><br /><span><strong>'._LAST.' 20 '._ARTICLES.'</strong></span><br /><br />';
	$result = $db->query("SELECT sid, aid, title, alanguage, display_order FROM {$db->TBL->stories}
		LEFT JOIN {$db->TBL->topics} AS t ON (topicid=topic)
		WHERE display_order = '0'
		  AND ptime<=".time()."
		ORDER BY ptime DESC
		LIMIT 20");
	if ($result->num_rows) {
		echo '<table>';
		while (list($sid, $said, $title, $alanguage, $display_order) = $result->fetch_row()) {
			$disporder = is_null($display_order) ? '&nbsp;': $display_order;
			if ($alanguage == '') { $alanguage = _ALL; }
			echo "<tr>
				<td><strong>$sid</strong></td>
				<td width=\"100%\"><a href=\"".URL::index("News&amp;file=article&amp;sid=$sid")."\">$title</a></td>
				<td>$alanguage</td>
				<td>$disporder</td>";
			if (can_admin('news')) {
				echo "<td nowrap=\"nowrap\">(<a href=\"".URL::admin("News&amp;edit=$sid").'">'._EDIT."</a>-<a href=\"".URL::admin("News&amp;del=$sid").'">'._DELETE."</a>-<a href=\"".URL::admin("News&amp;stick=$sid").'">'._STICK.'</a>)</td>';
			}
			echo '</tr>';
		}
		echo '</table>';
	} else {
		echo sprintf(_ERROR_NONE_TO_DISPLAY, strtolower(_ARTICLES));
	}

	CloseTable();
}
